<template>
    <picker mode="multiSelector" 
            :value="multiIndex" 
            :range="multiArray" 
            @change="handleValueChange"
            @columnchange="handleColumnChange">
        <slot></slot>
    </picker>
</template>

<script>
	import { getChannelTree } from "@/service/api/api.js";
	export default {
        props:{
            defaultRegions:{
                type:Array,
                default(){
                    return []
                }
            },
            defaultRegionCode:{
                type:String
            },
            defaultRegion:[String,Array],
			isSelectAll: {
				type: Boolean,
				default() {
					return true
				}
			}
        },
		data() {
			return {
                cityArr: [],
                multiIndex: [0, 0],
                isInitMultiArray:true,
				treeArr: []
			}
		},
        watch:{
            defaultRegion:{
                handler(region,oldRegion){
                    if(Array.isArray(region)){
                        // 避免传的是字面量的时候重复触发
                        oldRegion = oldRegion || []
                        if(region.join('')!==oldRegion.join('')){
                            this.handleDefaultRegion(region)
                        }
                    }else if(region&&region.length == 6){
                        this.handleDefaultRegion(region)
                    }else{
                        console.warn('defaultRegion非有效格式')
                    }
                },
                immediate:true,
            },
			isSelectAll: {
				handler(newVal) {
					this.isSelectAll = newVal
				}
			}
        },
        computed:{
            multiArray(){
                return this.pickedArr.map(arr=>arr.map(item=>item.name))
            },
            pickedArr(){
                // 进行初始化
                if(this.isInitMultiArray){
                    return [
                        this.treeArr,
                        this.treeArr[0].children
                    ]
                }
                return [this.treeArr, this.cityArr];
            }
        },
		created() {
			this.init()
		},
		methods: {
			init() {
				getChannelTree({
					deptId: uni.getStorageSync('user_info').userDeptId || '',
					userId: uni.getStorageSync('user_info').userId || ''
				}).then(res => {
					if(res.data.code == '0') {
						if(this.isSelectAll) {
							res.data.data.unshift({
								channelId: "",
								children: [],
								name: "全部",
								id: ''
							})
							res.data.data.forEach((item,idx)=>{
								if(item.children && item.children.length > 0) {
									item.children.unshift({
										channelId: "",
										children: null,
										name: "全部"
									})
								} else {
									item.children = [{
										channelId: "",
										children: null,
										name: "全部"
									}]
								}
							})
						}
						
						this.treeArr = res.data.data
						this.cityArr = res.data.data && res.data.data.length > 0 ? res.data.data[0].children : []
					}
				})
			},
            handleColumnChange(e){
                this.isInitMultiArray = false;
                const that = this;
                let col = e.detail.column;
                let row = e.detail.value;
                that.multiIndex[col] = row;
                try{
                    switch(col){
                        case 0:
                            that.cityArr = this.treeArr[that.multiIndex[0]].children
                            break;
                        case 1:
                            break;
                    }
                }catch(e){
                }
                
            },
            handleValueChange(e){
                // 结构赋值
				// console.log(this.pickedArr)
                let [index0,index1] = e.detail.value;
                let [arr0,arr1] = this.pickedArr;
				
				// delete arr0[index0].children
                let address = [arr0[index0], arr1[index1]];
                
                this.$emit('getRegion', address)
            },
            handleDefaultRegion(region){
                const isCode = !Array.isArray(region)
				// console.log(region)
                this.isInitMultiArray = false;
                let children = this.treeArr
				
				let x = 0;
				let j = 0;
				for(let i=0; i < children.length;i++){
					if(children[i].channelId == region['0']) {
						x = i;
						this.cityArr = children[i].children
						
						this.cityArr.forEach((item,idx) =>{
							if(item.channelId == region['1']) {
								j = idx
							}
						})
						
						break;
					}else{
					   // 首次匹配失败就用默认的初始化
					   // console.log(i,j,children.length-1);
					   if(i==0 && j==(children.length-1)){
						   this.isInitMultiArray = true;
					   }
                    }
				}
				
				if(children && children.length > 0 && (region['0'] != '0' && region['1'] != '0')) {
					this.$set(this.multiIndex,x,j)
					let address = [children[x], this.cityArr[j]];
					
					this.$emit('getRegion', address)
				}
            }
		},
	}
</script>
